package de.ur.iw.sql;

import java.util.ArrayList;

import de.ur.iw.interfaces.DataBaseListener;
import de.ur.iw.wiki.WikiPage;

public class DataBaseSaver extends Thread{
	
	private ArrayList<DataBaseListener> listeners = new ArrayList<DataBaseListener>();

	private WikiSQLHelper db;
	
	private ArrayList<WikiPage> path;
	
	public DataBaseSaver(WikiSQLHelper database) {
		db = database;
	}
	
	public void addListener(DataBaseListener lst){
		if(!listeners.contains(lst)){
			listeners.add(lst);
		}
	}
	
	public boolean removeListener(DataBaseListener lst){
		return listeners.remove(lst);
	}
	
	@Override
	public void run() {
		try{
			db.insertPath(path);
			notifyListeners(null);
		}catch(Exception e){
			e.printStackTrace();
			notifyListeners(e);
		}
	}

	private void notifyListeners(Exception e) {
		for(int i=0; i<listeners.size(); i++){
			listeners.get(i).onDataBaseSavingFinished(e);
		}
	}

	public void insert(ArrayList<WikiPage> path) {
		this.path = path;
		start();
	}
	
}
